package com.hxzy.controller.system;

import com.hxzy.common.annotation.Log;
import com.hxzy.common.constant.UserConstants;
import com.hxzy.common.core.controller.BaseController;
import com.hxzy.common.core.domain.AjaxResult;
import com.hxzy.common.core.domain.R;
import com.hxzy.common.core.domain.entity.SysDept;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.enums.BusinessType;
import com.hxzy.common.utils.StringUtils;
import com.hxzy.system.domain.dto.SysDeptSearchDTO;
import com.hxzy.system.domain.dto.ValueExistsDTO;
import com.hxzy.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "部门管理API")
@RestController
@RequestMapping(value = "/api/system/dept")
public class SysDeptController extends BaseController {


    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@hxzy.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public R list(SysDeptSearchDTO sysDeptSearchDTO)
    {
        List<SysDept> depts = this.sysDeptService.selectDeptList(sysDeptSearchDTO);
        return  R.okHasData(depts);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@hxzy.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysDept dept)
    {

        if (UserConstants.NOT_UNIQUE.equals(this.sysDeptService.checkDeptNameUnique(dept)))
        {
            R r=R.build(AckCode.FAIL);
            r.setMsg("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            return r;
        }

        return toAjax(this.sysDeptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@hxzy.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();

        if (UserConstants.NOT_UNIQUE.equals(this.sysDeptService.checkDeptNameUnique(dept)))
        {
            R r=R.build(AckCode.FAIL);
            r.setMsg("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            return r;
        }
        else if (dept.getParentId().equals(deptId))
        {
            R r=R.build(AckCode.FAIL);
            r.setMsg("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
            return r;
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && this.sysDeptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            R r=R.build(AckCode.FAIL);
            r.setMsg("该部门包含未停用的子部门");
            return r;
        }

        return toAjax(this.sysDeptService.updateDept(dept));
    }


}
